﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using ZHDJ.Core;
using ZHDJ.Core.Log;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.DataCaching;
using ZHDJ.Data.Models.Box;
using ZHDJ.Data.Models.Common;
using ZHDJ.Data.Models.Org;
using ZHDJ.Web.CommonMethod;

namespace ZHDJ.Web
{
    public class Global : System.Web.HttpApplication
    {


        protected void Application_Start(object sender, EventArgs e)
        {
            //Database.SetInitializer(new AppBoxDatabaseInitializer());
            Database.SetInitializer<AppBoxContext>(null);//禁用生成
            Log4netHelper.SetConfig();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            var DB = HttpContext.Current.Items["__AppBoxContext"] as AppBoxContext ?? new AppBoxContext();
            try
            {
                var log = new PartyUserLoginLog();
                log.ID = StringHelper.NewID;
                log.LoginID = "";
                log.LoginIP = Request.UserHostAddress;
                log.LoginOutTime = null;
                log.LoginTime = DateTime.Now;
                log.SessionID = Session.SessionID;
                log.Source = 1;
                log.LastOpTime = DateTime.Now;
                DB.PartyUserLoginLogs.Add(log);
                DB.SaveChanges();
                Session["UserLogID"] = log.ID;
            }
            catch (Exception ex)
            {
                Log4netHelper.WriteLog("用户登陆日志", ex);
            }
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {


        }

        protected virtual void Application_EndRequest()
        {
            var context = HttpContext.Current.Items["__AppBoxContext"] as AppBoxContext;
            if (context != null)
            {
                context.Dispose();
            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity iden = (FormsIdentity)(HttpContext.Current.User.Identity);
                        FormsAuthenticationTicket ticket = iden.Ticket;
                        string userdata = ticket.UserData;
                        string[] rolues = userdata.Split(',');
                        HttpContext.Current.User = new GenericPrincipal(iden, rolues);
                    }
                }
            }
        }

        //protected void Application_Error(object sender, EventArgs e)
        //{
        //    Exception ex = Server.GetLastError().GetBaseException(); //获取异常源
        //    if (ex != null)
        //    {
        //        Log4netHelper.WriteLog(ex);
        //    }
        //    var toP = ConfigurationManager.AppSettings["IsGoErrorPage"] ?? "1";
        //    if (toP != "1")
        //    {

        //        return;
        //    }
        //    Server.ClearError();
        //    var url = Request.Url.ToString().ToLower();
        //    if (url.Contains("datacount=") || (url.Contains("pageindex=") && url.Contains("pagesize=")))
        //    {
        //        //清空前一个异常

        //        Response.Write("{\"message\":\"系统异常\"}");
        //        Response.End();
        //    }
        //    else
        //    {
        //        string webHost = SystemParameterCaching.Get(SystemParameterKey.WebHost);
        //        HttpException ev = ex as HttpException;
        //        if (ev != null)
        //        {
        //            if (ev.GetHttpCode() == 404)
        //            {

        //                Response.Redirect(webHost + "/Errors/NotFoundFile.aspx");
        //                return;
        //            }
        //        }


        //        //Server.Transfer(webHost + "/Errors/Error.aspx");
        //        Response.Redirect(webHost + "/Errors/Error.aspx");
        //        //Response.End();

        //    }
        //}

        protected void Session_End(object sender, EventArgs e)
        {
            /*
             * 当执行SessionEnd事件时，根据当前日期和UserID修改当前登录人的是否在线状态为false
             */
            if (Session["PartyOrgMember"] != null)
            {
                PartyOrgMember user = Session["PartyOrgMember"] as PartyOrgMember;
                DataTable dt = Data.MySqlHelper.ExecuteDataSet(string.Format("select * from tblpartyvisitstatisticlogin where UserID='{0}' and AddDate='{1}'", user.LoginID, DateTime.Now.ToString("yyyy-MM-dd"))).Tables[0];
                if (dt.Rows.Count == 0)
                    StatisticMethod.Addpartyvisitstatistictwo(user, false);
                else
                    StatisticMethod.Updatepartyvisitstatistictwo(false, user.LoginID);
            }

        }

        protected void Application_End(object sender, EventArgs e)
        {
        }

    }
}